﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Web;
using System.Net;

namespace Meraz.Core.Helpers
{
    public class WebUtil
    {
        /// <summary>
        /// I could instead pass an IHttpRequest object for mocking
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static IEnumerable<string> FindInQueryString(NameValueCollection queryString, string key)
        {
            if (string.IsNullOrEmpty(key) || !queryString.AllKeys.Contains(key))
                return null;
            return queryString.GetValues(key);
        }
        public static string FindFirstInQueryString(NameValueCollection queryString, string key)
        {
            if (string.IsNullOrEmpty(key) || !queryString.AllKeys.Contains(key))
                return null;
            string[] values = queryString.GetValues(key);
            if (values.Length > 0)
                return values[0];
            return null;
        }
        public static bool TryFindFirstIntInQueryString(NameValueCollection queryString, string key, out int result)
        {
            result = int.MinValue;
            if (string.IsNullOrEmpty(key) || !queryString.AllKeys.Contains(key))
            {
                return false;
            }
            string[] values = queryString.GetValues(key);
            if (values.Length > 0)
            {
                int parsed;
                if (int.TryParse(values[0], out parsed))
                    result = parsed;
            }
            return result > int.MinValue;
        }
        public static bool TryFindFirstIntInQueryString(HttpRequest request, string key, out int result)
        {
            result = int.MinValue;
            if (string.IsNullOrEmpty(key) || !request.QueryString.AllKeys.Contains(key))
            {
                return false;
            }
            string[] values = request.QueryString.GetValues(key);
            if (values.Length > 0)
            {
                int parsed;
                if (int.TryParse(values[0], out parsed))
                    result = parsed;
            }
            return result > int.MinValue;
        }
        public static IEnumerable<int> FindIntsInQueryString(NameValueCollection queryString, string key)
        {
            if (string.IsNullOrEmpty(key) || !queryString.AllKeys.Contains(key))
                return new int[0];
            string[] values = queryString.GetValues(key);
            List<int> list = new List<int>();
            if (values.Length > 0)
            {
                int result;
                if (int.TryParse(values[0], out result))
                    list.Add(result);
            }
            return list;
        }

    }
}
